import { useEffect, useState } from 'react'
import { getInterviewTitleAsync } from '../redux/interviewSlice.js'
import { useSelector, useDispatch } from 'react-redux'
import { getListAsync } from '../redux/typeSlice'
import PageHeader from '../components/PageHeader'
import styles from '../css/Interview.module.css'
import { Tree } from 'antd'
import { getInterviewById } from '../api/interview.js'
export default function Interviews() {
  const dispatch = useDispatch()
  const { interviewList } = useSelector((state) => state.interview)
  const { typeList } = useSelector((state) => state.type)
  const [treeData, setTreeData] = useState([])
  // 该状态用于存储 id 对应的面试题内容
  const [interviewInfo, setInterviewInfo] = useState(null)
  const clickHandle = async (id) => {
    const { data } = await getInterviewById(id)
    setInterviewInfo(data)
  }
  useEffect(() => {
    if (!interviewList.length) {
      dispatch(getInterviewTitleAsync())
    }
    if (!typeList.length) {
      dispatch(getListAsync())
    }
    if (interviewList.length && typeList.length) {
      const arr = [] // 最终组装的数据会放入到该数组中
      for (let i = 0; i < typeList.length; i++) {
        arr.push({
          title: <h3 style={{ fontWeight: '200' }}>{typeList[i].typeName}</h3>,
          key: i,
        })
      }
      for (let i = 0; i < interviewList.length; i++) {
        const childArr = []
        for (let j = 0; j < interviewList[i].length - 1; j++) {
          childArr.push({
            title: (
              <h4 style={{ fontWeight: '200' }} onClick={() => clickHandle(interviewList[i][j]._id)}>
                {interviewList[i][j].interviewTitle}
              </h4>
            ),
            key: `${i}-${j}`,
          })
        }
        arr[i].children = childArr
      }
      setTreeData(arr)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [interviewList, typeList])
  // console.log('treeData', treeData)
  let interviewRightSide = null
  if (interviewInfo) {
    // 赋值为面试题的内容
    interviewRightSide = (
      <div className={styles.content}>
        <h1 className={styles.interviewRightTitle}>{interviewInfo?.interviewTitle}</h1>
        <div className={styles.contentContainer}>
          <div dangerouslySetInnerHTML={{ __html: interviewInfo?.interviewContent }}></div>
        </div>
      </div>
    )
  } else {
    interviewRightSide = (
      <div
        style={{
          textAlign: 'center',
          fontSize: '40px',
          fontWeight: '100',
          marginTop: '150px',
        }}
      >
        请在左侧选择面试题
      </div>
    )
  }

  return (
    <div className={styles.container}>
      <PageHeader title="面试题大全" />
      <div className={styles.interviewContainer}>
        <div className={styles.leftSide}>
          <Tree treeData={treeData} />
        </div>
        <div className={styles.rightSide}>{interviewRightSide}</div>
      </div>
    </div>
  )
}
